package cn.green.mapper.model.impls.table;

import cn.green.core.model.QTableModel;
import cn.green.mapper.exceptions.EntityTableMapperException;
import cn.green.mapper.model.EntityDataMapper;
import cn.green.mapper.model.FieldColumnMapper;
import cn.green.mvc.entity.OrmTableEntity;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;

import java.util.List;

/**
 * @author wang.yishu
 * @version 1.0
 * @className EntityTableMapper
 * @description 实体与表映射
 * @date 2025/7/23 10:10
 */
@Data
public class EntityTableMapper implements EntityDataMapper {
    //实体类
    private Class<OrmTableEntity> entityClass;
    //数据表
    private QTableModel tableModel;
    //属性字段映射
    private List<FieldColumnMapper> fieldColumnMappers;

    @Override
    public <T extends OrmTableEntity> T toEntity(JSONObject row) {
        if (row != null && fieldColumnMappers != null && !fieldColumnMappers.isEmpty()) {
            FieldColumnMapper pointer = null;
            try {
                OrmTableEntity ormTableEntity = entityClass.newInstance();
                for (FieldColumnMapper fieldColumnMapper : fieldColumnMappers) {
                    pointer = fieldColumnMapper;
                    fieldColumnMapper.setFieldValue(row, ormTableEntity);
                }
                return (T) ormTableEntity;
            } catch (Exception e) {
                throw new EntityTableMapperException(e, pointer);
            }

        }
        return null;
    }

    @Override
    public <T extends OrmTableEntity> JSONObject toJson(T ormTableEntity) {
        JSONObject row = new JSONObject();
        if (ormTableEntity != null && fieldColumnMappers != null && !fieldColumnMappers.isEmpty()) {
            for (FieldColumnMapper fieldColumnMapper : fieldColumnMappers) {
                try {
                    fieldColumnMapper.setColumnValue(row, ormTableEntity);
                } catch (Exception e) {
                    throw new EntityTableMapperException(e, fieldColumnMapper);
                }
            }
        }
        return row;
    }

}
